package com.syl.starter.itools.framework.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.syl.starter.itools.base.utils.LogUtils;
import com.syl.starter.itools.common.utils.StringUtils;
import com.syl.starter.itools.framework.utils.help.BaseXMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author syl
 * @create 2018-09-28 20:37
 **/
public class JsonUtils extends BaseXMapper {
    public static final String ARRAY_SYMBOL_START = "[";
    public static final String ARRAY_SYMBOL_END = "]";
    private static Logger LOG = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * 判断json字符串是否数组
     * @param json
     * @return
     */
    public static boolean isArray(String json){
        JsonNode node = getNode(json);
        if(node == null)
            return false;
        return node.isArray();
    }

    /**
     * 获取json节点
     * @param json
     * @return
     */
    public static JsonNode getNode(String json){
        ObjectMapper mapper = JsonUtils.getObjectMapper(true);
        try {
            return mapper.readTree(json);
        } catch (IOException e) {
            LogUtils.error(LOG,"转换失败 json不合法", e);
        }
        return null;
    }

    /**
     * 把对象转换为json 默认过滤null值
     * @param object java对象
     * @return 失败时返回null
     */
    public static String toJson(Object object){
        return toJson(object, true);
    }

    /**
     * 把对象转换为json
     * @param object java对象
     * @return 失败时返回null
     */
    public static String toJson(Object object, boolean noNull){
        if(noNull)
            return toJson(object, JsonInclude.Include.NON_NULL);
        return toJson(object,null);
    }

    /**
     * 把对象转换为json
     * @param object java对象
     * @param strategy 转换策略
     * @return 失败时返回null
     */
    public static String toJson(Object object, JsonInclude.Include strategy){
        return xToString(new ObjectMapper(), object, strategy);
    }

    /**
     * 从流中把json转换为java bean 默认非严格模式
     * @param inputStream
     * @param cz
     * @param <T>
     * @return 失败时返回null
     */
    public static <T> T fromJson(InputStream inputStream, Class<T> cz){
        return fromJson(inputStream, cz, false);
    }

    /**
     * 从流中把json转换为java bean
     * @param inputStream
     * @param cz
     * @param <T>
     * @param strict 是否严格模式
     * @return 失败时返回null
     */
    public static <T> T fromJson(InputStream inputStream, Class<T> cz, boolean strict){
        if(inputStream == null)
            return null;
        ObjectMapper mapper = getObjectMapper(strict);
        try {
            return mapper.readValue(inputStream,cz);
        } catch (IOException e) {
            LogUtils.error(LOG,"转换失败  ", e);
            return null;
        }
    }

    /**
     * 把json转换为java bean 默认非严格模式
     * @param json
     * @param cz
     * @param <T>
     * @return 失败时返回null
     */
    public static <T> T fromJson(String json, Class<T> cz){
        return fromJson(json, cz, false);
    }

    /**
     * 把json转换为java bean
     * @param json
     * @param cz
     * @param <T>
     * @param strict 是否严格模式
     * @return 失败时返回null
     */
    public static <T> T fromJson(String json, Class<T> cz, boolean strict){
        if(StringUtils.isEmptyAndTrim(json))
            return null;
        try {
            ObjectMapper mapper = getObjectMapper(strict);
            return mapper.readValue(json,cz);
        } catch (IOException e) {
            LogUtils.error(LOG,"转换失败 json不合法", e);
            return null;
        }
    }

    /**
     * 转换json数组为bean数组 严格模式
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T[] fromJsonArray(String json, Class<T> tClass){
        JsonNode node = JsonUtils.getNode(json);
        Object array = Array.newInstance(tClass, node.size());
        for (int i = 0; i < node.size(); i++) {
            String tempJson = node.get(i).toString();
            Array.set(array, i, JsonUtils.fromJson(tempJson, tClass));
        }
        return (T[]) array;
    }

    /**
     * 简便的将json数组转换为 bean list 严格模式
     * @param json
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> List<T> fromJsonList(String json, Class<T> tClass){
        T[] ts = fromJsonArray(json, tClass);
        return Arrays.asList(ts);
    }

    /**
     * 转换json数组为bean list 默认非严格模式
     * @param json
     * @param typeReference 用法 new TypeReference<List<XXX>>(){}
     * 注意: 只有这么写才能原样转换为原bean对象
     * @return 失败时返回空集合
     */
    public static <T> List<T> fromJsonList(String json, TypeReference<List<T>> typeReference){
        // 这里一定不能 直接 new TypeReference<List<T>>(){} 这样会导致序列化后为LinkMap
        return fromJsonList(json, typeReference, false);
    }

    /**
     * 转换json数组为bean list
     * @param json
     * @param typeReference 用法 new TypeReference<List<XXX>>(){}
     * @param <T>
     * @param strict 是否严格模式
     * @return 失败时返回空集合
     */
    public static <T> List<T> fromJsonList(String json, TypeReference typeReference, boolean strict){
        if(StringUtils.isEmptyAndTrim(json))
            return Collections.EMPTY_LIST;
        ObjectMapper mapper = getObjectMapper(strict);
        try {
            Type type = typeReference.getType();
            LOG.debug("type name {}", type.getTypeName());
            return mapper.readValue(json, typeReference);
        } catch (IOException e) {
            LogUtils.error(LOG,"转换失败 json不合法", e);
            return Collections.EMPTY_LIST;
        }
    }

    /**
     * 定制ObjectMapper
     * @param strict
     * @return
     */
    public static ObjectMapper getObjectMapper(boolean strict){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, strict);
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, strict);
//        mapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, strict);
        return mapper;
    }

    /**
     * 设置xml到输出流中 默认以UTF-8输出
     * @param json
     * @param out
     * @return
     */
    public static boolean outputStream(OutputStream out, String json){
        if(out == null || json == null)
            return false;
        if(StringUtils.isEmptyAndTrim(json))
            return false;
        try {
            ObjectMapper mapper = getObjectMapper(true);
            mapper.writeValue(out,json);
            return true;
        } catch (IOException e) {
            LogUtils.error(LOG, "输入输出流异常", e);
            return false;
        }
    }

    /**
     * 设置xml到输出流中
     * @param json
     * @param out
     * @param enc 编码
     * @return
     */
    public static boolean outputStream(String json, OutputStream out, JsonEncoding enc){
        if(out == null || json == null)
            return false;
        if(StringUtils.isEmptyAndTrim(json))
            return false;
        if(enc == null)
            return outputStream(out, json);
        try {
            ObjectMapper mapper = getObjectMapper(true);
            JsonGenerator generator = mapper.getFactory().createGenerator(out, enc);
            mapper.writeValue(generator,json);
            return true;
        } catch (IOException e) {
            LogUtils.error(LOG, "输入输出流异常", e);
            return false;
        }
    }

}
